package com.wzh.musichome.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzh.musichome.common.ConstantCode;
import com.wzh.musichome.common.ResponseTemplate;
import com.wzh.musichome.entity.dto.SingerDTO;
import com.wzh.musichome.entity.dto.SingerSearchDTO;
import com.wzh.musichome.entity.pojo.Singer;
import com.wzh.musichome.service.SingerService;
import com.wzh.musichome.utils.FastdfsClientUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

/**
 * <p>
 * 歌手 前端控制器
 * </p>
 *
 * @author wzh
 * @since 2020-12-10
 */
@RestController
@RequestMapping("/singer")
public class SingerController {

    @Autowired
    private SingerService singerService;


    @Autowired
    private FastdfsClientUtil fastdfsClientUtil;

    @PostMapping("/add")
    public Object addSinger(@RequestBody SingerDTO singerDTO) {
        Singer singer = new Singer();
        BeanUtils.copyProperties(singerDTO, singer);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");    //格式化规则
        Date date = singerDTO.getBirth();         //获得你要处理的时间 Date型
        String strDate = sdf.format(date); //格式化成yyyy-MM-dd格式的时间字符串
        Date newDate = null;
        try {
            newDate = sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        java.sql.Date birth = new java.sql.Date(newDate.getTime());//最后转换成 java.sql.Date类
        singer.setBirth(birth);
        try {
            boolean b = singerService.save(singer);
            if (b) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("新增成功");
                return data;
            }
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_INSERT, "新增失败！！ 具体原因" + e.getMessage());
        }
        return 0;
    }

    @PostMapping("/delete/{id}")
    public Object deleteSinger(@PathVariable Integer id) {
        try {
            boolean b = singerService.removeById(id);
            if (b) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("删除成功");
                return data;
            }
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_DELETE, "删除失败！！ 具体原因" + e.getMessage());
        }
        return 0;
    }

    @PostMapping("/update")
    public Object updateSinger(@RequestBody Singer singer) {
        Singer ori = singerService.getById(singer.getId());
        BeanUtils.copyProperties(singer, ori);
        try {
            boolean b = singerService.saveOrUpdate(ori);
            if (b) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("更新成功");
                return data;
            }
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPDATE, "更新失败！！ 具体原因" + e.getMessage());
        }
        return 0;
    }

    @GetMapping("/selectByPrimaryKey/{id}")
    public Object selectByPrimaryKey(@PathVariable Integer id) {
        try {
            Singer singer = singerService.getById(id);
            if (singer != null) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("查询成功");
                data.setData(singer);
                return data;
            }
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "未找到对应歌手");
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查询失败！！ 具体原因" + e.getMessage());
        }
    }


    @GetMapping("/singerOfSex")
    public Object singerOfSex(@RequestParam(required = false) Long current, @RequestParam(required = false) Long size, @RequestParam String sex) {
        QueryWrapper<Singer> wrapper = new QueryWrapper<>();
        ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
        try {
            if (current != null && size != null) {
                wrapper.eq("sex", sex);
                Page<Singer> page = new Page<>();
                page.setCurrent(current);
                page.setSize(size);
                Page<Singer> list = singerService.page(page, wrapper);
                data.setMsg("查询成功");
                data.setData(list);
            } else {
                wrapper.eq("sex", sex);
                List<Singer> list = singerService.list(wrapper);
                if (list.size() != 0) {
                    data.setMsg("查询成功");
                    data.setData(list);
                }
            }
            return data;
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查询失败！！ 具体原因" + e.getMessage());
        }
    }

    @PostMapping("/singerOfSexAndName")
    public Object singerOfSexAndName(@RequestBody SingerSearchDTO searchDTO) {
        QueryWrapper<Singer> wrapper = new QueryWrapper<>();
        ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
        Long current = searchDTO.getCurrent();
        Long size = searchDTO.getSize();
        String name = searchDTO.getName();
        String sex = searchDTO.getSex();
        System.out.println(name + sex);
        Page<Singer> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
            if (name == null || sex == null) {
                wrapper.like("name", name).or().like("sex", sex);
            } else if (name != null && sex != null) {
                wrapper.like("name", name).like("sex", sex);
            }
        try {
            Page<Singer> list = singerService.page(page,wrapper);
            if (list.getTotal() > 0) {
                data.setMsg("查询成功");
                data.setData(list);
            } else {
                data.setFlag(false);
                data.setMsg("没有相关歌手");
            }
            return data;
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查询失败！！ 具体原因" + e.getMessage());
        }
    }

    @GetMapping("/selectALL")
    public Object selectALL(@RequestParam(required = false) Long current, @RequestParam(required = false) Long size) {
        try {
            if (current != null && size != null) {
                Page<Singer> page = new Page<>();
                page.setCurrent(current);
                page.setSize(size);
                Page<Singer> list = singerService.page(page);
                if (list.getTotal() != 0) {
                    ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                    data.setMsg("查询成功");
                    data.setData(list);
                    return data;
                }
            } else {
                List<Singer> list = singerService.list();
                if (list.size() != 0) {
                    ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                    data.setMsg("查询成功");
                    data.setData(list);
                    return data;
                }
            }
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查询失败！！ 具体原因" + e.getMessage());
        }
        return 0;
    }

    @GetMapping("/selectOfName")
    public Object selectOfName(@RequestParam String name) {
        try {
            QueryWrapper<Singer> wrapper = new QueryWrapper<>();
            wrapper.like("name", name);
            List<Singer> list = singerService.list(wrapper);
            if (list.size() != 0) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("查询成功");
                data.setData(list);
                return data;
            }
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查询失败！！ 具体原因" + e.getMessage());
        }
        return 0;
    }

    /**
     * 更新歌手图片
     */
    @PostMapping("/updateSingerPic")
    public Object updateSingerPic(@RequestParam("file") MultipartFile avatorFile, @RequestParam("id") int id) {

        try {
            Singer byId = singerService.getById(id);
            if (!byId.getPic().equals(ConstantCode.defaultImgUrl)) {
                String[] split = byId.getPic().split("\\.");
                String sltUrl = split[0] + "_60x60." + split[1];
                fastdfsClientUtil.deleteFile(byId.getPic());
                fastdfsClientUtil.deleteFile(sltUrl);
            }
            String url = fastdfsClientUtil.upload(avatorFile);
            Singer singer = new Singer();
            singer.setId(id);
            singer.setPic(url);
            boolean flag = singerService.saveOrUpdate(singer);
            if (flag) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("头像更改成功");
                return data;
            }
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片更改失败");
        } catch (IOException e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片更改失败" + e.getMessage());
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片更改失败" + e.getMessage());
        }
    }

}
